package com.ddyx.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ddyx.common.util.BeanUtil;
import com.ddyx.common.util.DateUtil;
import com.ddyx.common.util.RequestForm;
import com.ddyx.common.util.ResponseForm;
import com.ddyx.common.util.ResponseJson;
import com.ddyx.entity.Task;
import com.ddyx.entity.TaskGroup;
import com.ddyx.mapper.TaskGroupMapper;
import com.ddyx.mapper.TaskMapper;
import com.ddyx.service.ITaskService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("iTaskService")
public class TaskServiceImpl implements ITaskService {

	@Resource
	TaskMapper taskMapper;
	
	@Resource
	TaskGroupMapper taskGroupMapper;

	@SuppressWarnings("unchecked")
	@Override
	public String getTaskInfoByIdPage(RequestForm requestForm) {
		Map<String, Object> params = (Map<String, Object>) requestForm.getData();
		int size = params.get("size") == null ? 0 : Integer.valueOf(params.get("size") + "");
		int page = params.get("page") == null ? 0 : Integer.valueOf(params.get("page") + "");
		int start = 0;
		if (size < 1)
			size = 20;// 默认每页20条
		if (page < 1)
			page = 1;// 默认第1页
		start = (page - 1) * size;
		params.put("start", start);
		params.put("size", size);
		params.put("targetUser", requestForm.getUserId());
		this.convertParamMap(params);
		int total = taskMapper.getTaskInfoCount(params);
		List<Task> taskList = taskMapper.getTaskInfoById(params);
		return ResponseJson.getInstance().setPage(page).setSize(size).setTotal(total).setData(taskList).toString();
	}

	@Transactional
	@Override
	public ResponseForm addTask(RequestForm requestForm) {
		String userId = requestForm.getUserId();
		String placeId = requestForm.getPlaceId();
		ResponseForm res = new ResponseForm();
		try {
			Task task = BeanUtil.parseBean(requestForm, new Task());
			// 设置默认属性
			task.setBeginTime(DateUtil.getNow());
			task.setIsReaded("0");
			task.setTaskStatus("0");
			task.setCreateUser(userId);
			int result = taskMapper.addTask(task);
			
			if(StringUtils.isNotBlank(task.getTaskGroup())){
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("taskGroup", task.getTaskGroup());
				param.put("wfTaskId", task.getWfTaskId());
				boolean isExits = taskGroupMapper.getIsExtis(param)>0?true:false;
				if(isExits){
					taskGroupMapper.deleteTaskGroup(param);
				}
				TaskGroup taskGroup = BeanUtil.parseBean(requestForm, new TaskGroup());
				taskGroup.setCreateUser(userId);
				taskGroup.setCreateTime(DateUtil.format_ymd_hms.format(new Date()));
				taskGroup.setPlaceId(placeId);
				
				taskGroupMapper.addTaskGroup(taskGroup);
			}
			
			if (result < 0) {
				res.setStatus(false);
				res.setMessage("添加任务失败");
			}
		} catch (Exception e) {
			res.setStatus(false);
			res.setMessage("参数解析错误");
			log.error("添加任务失败 "+e);
		}
		return res;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ResponseForm deleteTask(RequestForm requestForm) {
		ResponseForm res = new ResponseForm();
		try {
			Map<String, Object> params = (Map<String, Object>) requestForm.getData();
			int result = taskMapper.deleteTask(params);
			if (result < 0) {
				res.setStatus(false);
				res.setMessage("删除任务失败");
			}
		} catch (Exception e) {
			res.setStatus(false);
			res.setMessage("删除任务失败");
			log.error("删除任务失败"+e);
		}
		return res;
	}

	@Override
	public ResponseForm modifyTask(RequestForm requestForm) {
		ResponseForm res = new ResponseForm();
		String userId = requestForm.getUserId();
		String placeId = requestForm.getPlaceId();
		try {
			Task task = BeanUtil.parseBean(requestForm, new Task());
			int result = taskMapper.modifyTask(task);
			
			if(StringUtils.isNotBlank(task.getTaskGroup())){
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("taskGroup", task.getTaskGroup());
				param.put("wfTaskId", task.getWfTaskId());
				boolean isExits = taskGroupMapper.getIsExtis(param)>0?true:false;
				if(isExits){
					taskGroupMapper.deleteTaskGroupByTaskId(param);
				}
				TaskGroup taskGroup = BeanUtil.parseBean(requestForm, new TaskGroup());
				taskGroup.setCreateUser(userId);
				taskGroup.setCreateTime(DateUtil.format_ymd_hms.format(new Date()));
				taskGroup.setPlaceId(placeId);
				
				taskGroupMapper.addTaskGroup(taskGroup);
			}
			
			if (result < 0) {
				res.setStatus(false);
				res.setMessage("修改任务失败");
			}
		} catch (Exception e) {
			res.setStatus(false);
			res.setMessage("参数解析错误");
			log.error("修改任务失败"+e);
		}
		return res;
	}

	/*
	 * private Map<String,Object> convertToMap(Object obj) throws Exception{
	 * Map<String, Object> reMap = new HashMap<String, Object>(); if (obj ==
	 * null) return null; Field[] fields = obj.getClass().getDeclaredFields();
	 * try { for (int i = 0; i < fields.length; i++) { Field f =
	 * obj.getClass().getDeclaredField(fields[i].getName());
	 * f.setAccessible(true); Object o = f.get(obj);
	 * reMap.put(fields[i].getName(), o); } } catch (SecurityException e) {
	 * e.printStackTrace(); } return reMap; }
	 */

	private void convertParamMap(Map<String, Object> params) {
		String status = params.get("status") == null ? null : params.get("status") + "";
		if (status == null) {
			return;
		}
		switch (status) {
		case "0":
			break;
		case "1":
			// 截止今天
			params.put("endTime", DateUtil.getToday_Ymd());
			break;
		case "2":
			// 截止本周
			params.put("beginTime", DateUtil.getFirstDayOfThisWeek_Ymd());
			params.put("endTime", DateUtil.getLastDayOfThisWeek_Ymd());
			break;
		case "3":
			// 逾期
			params.put("taskStatus", "0");
			params.put("endTime", DateUtil.getToday_Ymd());
			break;
		case "4":
			// 完成
			params.put("taskStatus", "1");
			break;
		default:
			break;
		}
	}
}
